package cn.leedsoft.and.crimeintent.controller.crime_intent;

import android.annotation.TargetApi;
import android.app.Activity;
import android.content.Intent;
import android.os.Build;
import android.os.Bundle;
import android.support.v4.app.ListFragment;
import android.util.Log;
import android.view.*;
import android.widget.*;
import cn.leedsoft.and.crimeintent.R;
import cn.leedsoft.and.crimeintent.model.Crime;
import cn.leedsoft.and.crimeintent.model.CrimeLab;

import java.util.List;

/**
 * Created by leeds on 2016/8/8 10:44.
 */
public class CrimeListFragment extends ListFragment {
    private List<Crime> mCrimes;
    private static final String TAG = "CrimeListFragment";
    private static final int REQ_CODE_CRIME_DETAIL = 1;

    public static CrimeListFragment newInstance() {

        Bundle args = new Bundle();

        CrimeListFragment fragment = new CrimeListFragment();
        fragment.setArguments(args);
        return fragment;
    }

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        System.out.println(">>>>>>>>>>>>CrimeListFragment, onCreate");
        mCrimes = CrimeLab.getInstance(getActivity()).getCrimes();

        setListAdapter(new CrimeAdapter(mCrimes));

        setHasOptionsMenu(true);
    }

    @TargetApi(Build.VERSION_CODES.HONEYCOMB)
    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
        System.out.println(">>>>>>>>>>>>CrimeListFragment, onCreateView");

        View view = super.onCreateView(inflater, container, savedInstanceState);
        ListView listView = (ListView) view.findViewById(android.R.id.list);

        if (Build.VERSION.SDK_INT < Build.VERSION_CODES.HONEYCOMB) {
            registerForContextMenu(getListView());//注册浮动上下文菜单
        } else {//否则使用ActionMode
            listView.setChoiceMode(ListView.CHOICE_MODE_MULTIPLE_MODAL);
            listView.setMultiChoiceModeListener(new AbsListView.MultiChoiceModeListener() {
                @Override
                public void onItemCheckedStateChanged(ActionMode mode, int position, long id, boolean checked) {

                }

                @Override
                public boolean onCreateActionMode(ActionMode mode, Menu menu) {
                    getActivity().getMenuInflater().inflate(R.menu.fragment_crime_list_context, menu);
                    return true;
                }

                @Override
                public boolean onPrepareActionMode(ActionMode mode, Menu menu) {
                    return false;
                }

                @Override
                public boolean onActionItemClicked(ActionMode mode, MenuItem item) {
                    CrimeAdapter adapter = (CrimeAdapter) getListAdapter();
                    for (int i = 0; i < adapter.getCount(); i++) {
                        if (getListView().isItemChecked(i)) {
                            CrimeLab.getInstance(getActivity()).delCrime(adapter.getItem(i));
                        }
                    }
                    mode.finish();
                    adapter.notifyDataSetChanged();
                    return true;
                }

                @Override
                public void onDestroyActionMode(ActionMode mode) {

                }
            });
        }
        return view;
    }

    @Override
    public void onListItemClick(ListView l, View v, int position, long id) {
        Crime crime = ((CrimeAdapter) getListAdapter()).getItem(position);
        Log.d(TAG, crime.getTitle() + " is clicked");

        Intent intent = new Intent(getActivity(), DetailPagerActivity.class);
        intent.putExtra(CrimeDetailFragment.INTENT_KEY_CRIME_ID, crime.getId());
        startActivityForResult(intent, REQ_CODE_CRIME_DETAIL);//启动activity
    }

    @Override//统一的fragment之间传递消息的接收端
    public void onActivityResult(int requestCode, int resultCode, Intent data) {
        System.out.println(">>>>>>>>>>>>CrimeListFragment, onActivityResult");
        if (requestCode == REQ_CODE_CRIME_DETAIL) {
            Log.d(TAG, "onActivityResult");
        }
    }

    @Override
    public void onResume() {
        super.onResume();
        System.out.println(">>>>>>>>>>>>CrimeListFragment, onResume");

        ((CrimeAdapter) getListAdapter()).notifyDataSetChanged();
    }

    private class CrimeAdapter extends ArrayAdapter<Crime> {

        public CrimeAdapter(List<Crime> crimes) {
            super(getActivity(), 0, crimes);
        }

        @Override
        public View getView(int position, View convertView, ViewGroup parent) {
            if (convertView == null) {
                convertView = getActivity().getLayoutInflater().inflate(R.layout.fragment_list_item, null);
            }

            TextView title = (TextView) convertView.findViewById(R.id.crime_list_title);
            TextView date = (TextView) convertView.findViewById(R.id.crime_list_date);
            CheckBox solved = (CheckBox) convertView.findViewById(R.id.crime_list_solved);

            Crime crime = getItem(position);
            title.setText(crime.getTitle());
            date.setText(String.format("%tF", crime.getDate()));
            solved.setChecked(crime.isSolved());
            return convertView;
        }
    }

    @Override
    public void onCreateOptionsMenu(Menu menu, MenuInflater inflater) {
        super.onCreateOptionsMenu(menu, inflater);
        inflater.inflate(R.menu.fragment_crime_list, menu);
    }

    @TargetApi(11)
    @Override
    public boolean onOptionsItemSelected(MenuItem item) {
        switch (item.getItemId()) {
            case R.id.menu_crime_add:
                Crime crime = new Crime();
                CrimeLab.getInstance(getActivity()).addCrime(crime);
                Intent intent = new Intent(getActivity(), DetailPagerActivity.class);
                intent.putExtra(CrimeDetailFragment.INTENT_KEY_CRIME_ID, crime.getId());
                startActivityForResult(intent, CrimeListFragment.REQ_CODE_CRIME_DETAIL);
                return true;
            case R.id.menu_show_subtitle:
                if (getActivity().getActionBar().getSubtitle() == null) {
                    getActivity().getActionBar().setSubtitle(R.string.crime_subtitle);
                    item.setTitle(R.string.hide_subtitle);
                } else {
                    getActivity().getActionBar().setSubtitle(null);
                    item.setTitle(R.string.show_subtitle);
                }
                return true;
            default:
                return super.onOptionsItemSelected(item);
        }
    }

    @Override
    public void onCreateContextMenu(ContextMenu menu, View v, ContextMenu.ContextMenuInfo menuInfo) {
        super.onCreateContextMenu(menu, v, menuInfo);
        getActivity().getMenuInflater().inflate(R.menu.fragment_crime_list_context, menu);
    }

    //在onActivityCreated中，注册浮动上下文菜单
    @Override
    public boolean onContextItemSelected(MenuItem item) {
        AdapterView.AdapterContextMenuInfo menuInfo = (AdapterView.AdapterContextMenuInfo) item.getMenuInfo();
        CrimeAdapter adapter = (CrimeAdapter) getListAdapter();
        Crime crime = adapter.getItem(menuInfo.position);
        switch (item.getItemId()) {
            case R.id.menu_crime_delete:
                CrimeLab.getInstance(getActivity()).delCrime(crime);
                adapter.notifyDataSetChanged();
                return true;
            default:
                return super.onContextItemSelected(item);
        }
    }

    //fragment lifecycle
    @Override
    public void onDestroy() {
        super.onDestroy();
        System.out.println(">>>>>>>>>>>>CrimeListFragment, onDestroy");

        CrimeLab.getInstance(getActivity()).saveCrimes();
    }

    @Override
    public void onPause() {
        super.onPause();
        System.out.println(">>>>>>>>>>>>CrimeListFragment, onPause");
    }

    @TargetApi(Build.VERSION_CODES.HONEYCOMB)
    @Override
    public void onActivityCreated(Bundle savedInstanceState) {
        super.onActivityCreated(savedInstanceState);
        System.out.println(">>>>>>>>>>>>CrimeListFragment, onActivityCreated");
    }

    @Override
    public void onStart() {
        super.onStart();
        System.out.println(">>>>>>>>>>>>CrimeListFragment, onStart");
    }

    @Override
    public void onStop() {
        super.onStop();
        System.out.println(">>>>>>>>>>>>CrimeListFragment, onStop");
    }

    @Override
    public void onDestroyView() {
        super.onDestroyView();
        System.out.println(">>>>>>>>>>>>CrimeListFragment, onDestroyView");
    }

    @Override
    public void onAttach(Activity activity) {
        super.onAttach(activity);
        System.out.println(">>>>>>>>>>>>CrimeListFragment, onAttach");
    }

    @Override
    public void onDetach() {
        super.onDetach();
        System.out.println(">>>>>>>>>>>>CrimeListFragment, onDetach");
    }
}
